<?php

namespace Acme\UserBundle\Listener;

use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\HttpKernel;
use Acme\UserBundle\Entity\User;

class LogoutListener implements LogoutSuccessHandlerInterface {
	protected $context;
	protected $em;
	protected $router;
	public function __construct(SecurityContext $context, EntityManager $em, Router $router) {
		$this->context = $context;
		$this->em = $em;
		$this->router = $router;
	}
	
	/**
	 * Update the user "lastActivity" on each request
	 * 
	 * @param Request $request        	
	 */
	public function onLogoutSuccess(Request $request) {
		$user = $this->context->getToken ()->getUser ();
		$user->setLastActivity ( '0000-00-00 00:00:00' );
		$this->em->persist ( $user );
		$this->em->flush ();
		return new RedirectResponse ( $this->router->generate ( '_common_start' ) );
	}
}